/*
 * @ProjectName: flutter_common
 * @Package: 
 * @ClassName: audit_page.dart
 * @Description: 审核页面
 * @User: Page.Su
 * @Date: 2020/8/28
 * @Time: 17:02
 * @UpdateDate: 2020/8/28 17:02
 */

import 'dart:async';
import 'dart:io';

import 'package:fdottedline/fdottedline.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_su/common/app_color.dart';
import 'package:flutter_su/common/application.dart';
import 'package:flutter_su/common/fun.dart';
import 'package:flutter_su/common/language_text.dart';
import 'package:flutter_su/common/show.dart';
import 'package:flutter_su/enum/index_type.dart';
import 'package:flutter_su/enum/user_type.dart';
import 'package:flutter_su/provider/audit_line_provider.dart';
import 'package:flutter_su/router/Audit_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

class AuditPage extends StatefulWidget {
  @override
  _AuditPageState createState() => _AuditPageState();
}

class _AuditPageState extends State<AuditPage> {
  // 实现局部刷新
  final StreamController<String> _userTypeStream = StreamController();
  final StreamController<String> _userIdentityStream = StreamController();
  final StreamController<String> _nationalityStream = StreamController();
  final StreamController<bool> _disableShowStream = StreamController();

  // 输入框控制器
  final TextEditingController _personalNameController = TextEditingController();
  final TextEditingController _personalIdController = TextEditingController();
  final TextEditingController _companyChNameController =
      TextEditingController();
  final TextEditingController _companyChAddressController =
      TextEditingController();
  final TextEditingController _companyEnNameController =
      TextEditingController();
  final TextEditingController _companyEnAddressController =
      TextEditingController();

  // 根据是否是个人还是公司来显示隐藏输入框
  final StreamController<UserIdentity> _showPersonalOrCompanyStream =
      StreamController.broadcast();

  AuditLineProvider _auditLineProvider;

  String _userTypeData = ""; // 保存选择的类型
  int _userTypeIndex = -1;
  String _userIdentityData = ""; // 保存身份
  int _userIdentityIndex = -1;
  String _nationalityData = ""; // 保存国籍

  bool _isChina = false; // 国籍是不是选择了中国

  UserType _checkUserType = UserType.investors;
  UserIdentity _checkUserIdentity = UserIdentity.company;

  final ImagePicker _picker = ImagePicker(); // 打开图库

  // 维护一个Map，用于保存显示的图片
  Map<IndexType, File> _imageMap = {
    IndexType.zero: null,
    IndexType.one: null,
    IndexType.two: null,
    IndexType.three: null,
  };

  @override
  void initState() {
    _auditLineProvider = Provider.of<AuditLineProvider>(context, listen: false);
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    _userTypeStream.close();
    _userIdentityStream.close();
    _nationalityStream.close();
    _showPersonalOrCompanyStream.close();
    _disableShowStream.close();

    _personalNameController.dispose();
    _personalIdController.dispose();
    _companyChNameController.dispose();
    _companyChAddressController.dispose();
    _companyEnNameController.dispose();
    _companyEnAddressController.dispose();

    // 把provider的数据清除
    _auditLineProvider.clean();
    super.dispose();
  }

  final Widget _auditCommon = Container(
    child: Icon(
      Icons.keyboard_arrow_down,
      color: AppColor.MAIN_INPUT_COLOR,
    ),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: LanguageText.countryList,
        centerTitle: true,
        elevation: 0,
        backgroundColor: AppColor.MAIN_COLOR_BLUE,
      ),
      backgroundColor: AppColor.MAIN_COLOR_BLUE,
      body: _body(),
    );
  }

  Widget _body() {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Container(
        color: AppColor.TRANSPARENT,
        margin: EdgeInsets.only(
          top: SFunCommon.height(30),
          bottom: SFunCommon.height(20),
        ),
        child: RefreshIndicator(
          onRefresh: _onRefresh,
          child: SingleChildScrollView(
            child: _content(),
          ),
        ),
      ),
    );
  }

  // 执行下拉操作
  Future<void> _onRefresh() async {
    _imageMap.forEach((key, value) {
      _imageMap[key] = null;
    });
    _auditLineProvider.clean();

    _userTypeData = ""; // 保存选择的类型
    _userTypeIndex = -1; // 保存选择类型的下标
    _userIdentityData = ""; // 保存身份
    _userIdentityIndex = -1; // 保存身份类型的下标
    _nationalityData = ""; // 保存国籍
    _isChina = false; // 国籍是不是选择了中国
    _checkUserType = UserType.investors;
    _checkUserIdentity = UserIdentity.company;

    _userTypeStream.sink.add("");
    _userIdentityStream.sink.add("");
    _nationalityStream.sink.add("");
    _showPersonalOrCompanyStream.sink.add(UserIdentity.personal);

    _personalNameController.clear();
    _personalIdController.clear();
    _companyChNameController.clear();
    _companyChAddressController.clear();
    _companyEnNameController.clear();
    _companyEnAddressController.clear();

    setState(() {});
  }

  Widget _content() {
    return Container(
      margin: EdgeInsets.only(
        left: SFunCommon.width(33),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          _itemText("type", must: true),
          _typeOnTap(),
          _itemText("identity", must: true),
          _identityOnTap(),
          _itemText("nationality", must: true),
          _nationalityOnTap(),
          _showPersonalOrCompanyInput(),
          _registerButton(),
        ],
      ),
    );
  }

  // 控制显示个人还是公司
  Widget _showPersonalOrCompanyInput() {
    return StreamBuilder<UserIdentity>(
      initialData: UserIdentity.personal,
      stream: _showPersonalOrCompanyStream.stream,
      builder: (_, AsyncSnapshot<UserIdentity> snapshot) {
        if (snapshot.data == UserIdentity.company) {
          return Column(
            children: <Widget>[
              _inputChCompanyName(IndexType.two.index),
              _inputEnCompanyName(IndexType.four.index),
              _inputChCompanyAddress(IndexType.three.index),
              _inputEnCompanyAddress(IndexType.five.index),
              _idCardImage("companyCertificate",
                  IndexType.one.index),
            ],
          );
        } else if (snapshot.data == UserIdentity.personal && _isChina) {
          return Column(
            children: <Widget>[
              _inputPersonalName(IndexType.zero.index),
              _inputPersonalId(IndexType.one.index),
              _idCardImage(
                  "idCardFront", IndexType.two.index),
              _idCardImage(
                  "idCardBack", IndexType.three.index),
            ],
          );
        }
        return Column(
          children: <Widget>[
            _inputPersonalName(IndexType.zero.index),
            _inputPersonalId(IndexType.one.index),
            _idCardImage("passport", IndexType.zero.index),
          ],
        );
      },
    );
  }

  Widget _idCardImage(String key, int index) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        _itemText(key),
        _addImage(index),
      ],
    );
  }

  Widget _addImage(int index) {
    return Container(
      width: SFunCommon.width(600),
      height: SFunCommon.height(300),
      margin: EdgeInsets.only(
        top: SFunCommon.height(25),
        left: SFunCommon.width(40),
      ),
      decoration: BoxDecoration(
        border: Border.all(
          width: SFunCommon.width(2),
          color: Colors.white,
        ),
        borderRadius: BorderRadius.circular(SFunCommon.width(20)),
      ),
      child: _imageSelector(index),
    );
  }

  Widget _imageSelector(int index) {
    return Selector<AuditLineProvider, List<bool>>(
      builder: (BuildContext context, value, Widget child) {
        return _imageBox(value[index], index);
      },
      selector: (BuildContext context, AuditLineProvider auditLineProvider) {
        return auditLineProvider.listImage;
      },
      shouldRebuild: (pre, next) {
        return pre[index] == next[index] ? true : false;
      },
    );
  }

  // 图片显示区域
  Widget _imageBox(bool show, int index) {

    var onTap = ()async{
      var image = await _picker.getImage(source: ImageSource.gallery);
      if (image != null) {
        var file = File(image.path);
        _imageMap[IndexType.values[index]] = file;
        _auditLineProvider.setImageData(index, true);
      }
    };

    return show
        ? _image(onTap, index)
        : IconButton(
            icon: Icon(
              Icons.add,
              color: AppColor.MAIN_INPUT_COLOR,
            ),
            onPressed: onTap,
          );
  }

  // 图片widget
  Widget _image(onTap, int index) {
    return GestureDetector(
      child: Image.file(_imageMap[IndexType.values[index]]),
      onTap: onTap,
      onLongPress: () {
        _imageMap[IndexType.values[index]] = null;
        _auditLineProvider.setImageData(index, false);
      },
    );
  }

  // 每一行的提示
  Widget _itemText(String key, {bool must = false}) {
    Widget _mustWidget = must
        ? Text("*",
            style: SFunCommon.fontStyle(
              AppColor.MAIN_COLOR_CYAN,
              fontSize: 30,
            ))
        : Container(
            margin: EdgeInsets.only(
              left: SFunCommon.width(15),
            ),
          );

    Widget _text = Padding(
      padding: EdgeInsets.only(
        left: SFunCommon.width(20),
      ),
      child: LanguageText.auditText(key),
    );

    return Container(
      child: Row(
        children: <Widget>[
          _mustWidget,
          _text,
        ],
      ),
    );
  }

  // 类型可以点击
  Widget _typeOnTap() {
    return GestureDetector(
      onTap: () async {
        var data = await Application.router.navigateTo(
          context,
          AuditRouter.TYPE_IDENTITY + "/userType/$_userTypeIndex",
          transition: TransitionType.inFromRight,
        );
        if (data != null) {
          var list = data.toString().split("/");
          _userTypeIndex = int.parse(list.last);
          _userTypeData = list.first;
          _userTypeStream.sink.add(_userTypeData);

          // 保存枚举
          _checkUserType = UserType.values[_userTypeIndex];
          // 当选择了项目方的时候，身份只能是公司
          if (_checkUserType == UserType.projectParty) {
            // TODO 还没有写好
            _userIdentityStream.sink.add("公司");
            _showPersonalOrCompanyStream.sink.add(UserIdentity.company);
          } else {
            _userIdentityStream.sink.add(_userIdentityData);
          }
        }
      },
      child: StreamBuilder<String>(
        initialData: "",
        stream: _userTypeStream.stream,
        builder: (_, AsyncSnapshot<String> snapshot) {
          return _nextPageBox(snapshot.data ?? "");
        },
      ),
    );
  }

  // 身份点击区域
  Widget _identityOnTap() {
    return StreamBuilder<String>(
      initialData: "",
      stream: _userIdentityStream.stream,
      builder: (_, AsyncSnapshot<String> snapshot) {
        return GestureDetector(
          onTap: _checkUserType == UserType.projectParty
              ? _identityNoCanOnTap
              : _identityCanOnTap,
          child: _nextPageBox(snapshot.data ?? ""),
        );
      },
    );
  }

  // 身份能点击
  void _identityCanOnTap() async {
    var data = await Application.router.navigateTo(
      context,
      AuditRouter.TYPE_IDENTITY + "/identity/$_userIdentityIndex",
      transition: TransitionType.inFromRight,
    );
    if (data != null) {
      var list = data.toString().split("/");
      _userIdentityIndex = int.parse(list.last);
      _userIdentityData = list.first;
      _userIdentityStream.sink.add(_userIdentityData);

      // 保存枚举
      _checkUserIdentity = UserIdentity.values[_userIdentityIndex];
      if (_checkUserIdentity == UserIdentity.company) {
        _showPersonalOrCompanyStream.sink.add(UserIdentity.company);
      } else {
        _showPersonalOrCompanyStream.sink.add(UserIdentity.personal);
      }
    }
  }

  // 不能点击
  void _identityNoCanOnTap() {
    Show.showMsgByProviderError(key: "mushBeCompany");
  }

  Widget _nationalityOnTap() {
    return GestureDetector(
      onTap: () async {
        String countryCode = _nationalityData?.split("/")?.last ?? "";
        var data = await Application.router.navigateTo(
          context,
          AuditRouter.COUNTRY_LIST + "/$countryCode",
          transition: TransitionType.inFromRight,
        );
        if (data != null) {
          // 返回一个{国家昵称/国家代码}
          List list = data.split("/");
          String country = list.first;
          String code = list.last;
          _nationalityStream.sink.add(country);
          // 如果是中国
          if (code == "CHN") {
            _isChina = true;
          } else {
            _isChina = false;
          }
          _showPersonalOrCompanyStream.sink.add(_checkUserIdentity);
        }
      },
      child: StreamBuilder<String>(
        initialData: "",
        stream: _nationalityStream.stream,
        builder: (_, AsyncSnapshot<String> snapshot) {
          return _nextPageBox(snapshot.data ?? "");
        },
      ),
    );
  }

  // 可以点击到下一个页面
  Widget _nextPageBox(String content) {
    return Container(
      color: AppColor.TRANSPARENT,
      height: SFunCommon.height(60),
      margin: EdgeInsets.only(
        left: SFunCommon.width(33),
        right: SFunCommon.width(52),
        bottom: SFunCommon.height(30),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          _userTypeText(content),
          _auditCommon,
        ],
      ),
    );
  }

  // 盒子里面的文字内容
  Widget _userTypeText(String content) {
    return Container(
      child: Text(
        content,
        style: SFunCommon.fontStyle(
          AppColor.MAIN_INPUT_COLOR,
          fontSize: 36,
        ),
      ),
    );
  }

  Widget _inputPersonalName(int index) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        _itemText("userName", must: true),
        _textField(index, _personalNameController),
        _lineSelector(index),
      ],
    );
  }

  Widget _inputPersonalId(int index) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        _itemText("userId", must: true),
        _textField(index, _personalIdController),
        _lineSelector(index),
      ],
    );
  }

  Widget _inputChCompanyName(int index) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        _itemText("companyName"),
        _textField(index, _companyChNameController),
        _lineSelector(index),
      ],
    );
  }

  Widget _inputChCompanyAddress(int index) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        _itemText("companyAddress"),
        _textField(index, _companyChAddressController),
        _lineSelector(index),
      ],
    );
  }

  Widget _inputEnCompanyName(int index) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        _itemText("companyNameEn", must: true),
        _textField(index, _companyEnNameController),
        _lineSelector(index),
      ],
    );
  }

  Widget _inputEnCompanyAddress(int index) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        _itemText("companyAddressEn", must: true),
        _textField(index, _companyEnAddressController),
        _lineSelector(index),
      ],
    );
  }

  // 公共的textField
  Widget _textField(int index, TextEditingController controller) {
    return Container(
      width: SFunCommon.width(500),
      height: SFunCommon.height(55),
      margin: EdgeInsets.only(
        left: SFunCommon.width(40),
        top: SFunCommon.height(10),
      ),
      child: TextField(
        keyboardType: TextInputType.emailAddress,
        controller: controller,
        autofocus: false,
        style: SFunCommon.fontStyle(
          AppColor.MAIN_INPUT_COLOR,
          fontSize: 36,
        ),
        cursorColor: AppColor.MAIN_INPUT_COLOR,
        decoration: _inputDecoration(),
        onChanged: (value) {
          if (value.isEmpty) {
            _auditLineProvider.setInputData(index, false);
          } else {
            _auditLineProvider.setInputData(index, true);
          }
        },
      ),
    );
  }

  // 局部刷新：下划线
  Widget _lineSelector(int index) {
    return Selector<AuditLineProvider, List<bool>>(
      builder: (BuildContext context, value, Widget child) {
        return _line(value[index]);
      },
      selector: (BuildContext context, AuditLineProvider auditLineProvider) {
        return auditLineProvider.listInput;
      },
      shouldRebuild: (pre, next) {
        return pre[index] == next[index] ? true : false;
      },
    );
  }

  // 一条虚线
  Widget _line(bool data) {
    return Container(
      margin: EdgeInsets.only(
        bottom: SFunCommon.height(40),
        left: SFunCommon.width(40),
      ),
      child: Offstage(
        offstage: data,
        child: FDottedLine(
          color: Colors.white,
          width: SFunCommon.width(336),
          strokeWidth: 2.0,
          dottedLength: 10.0,
          space: 2.0,
        ),
      ),
    );
  }

  // 输入框装饰器
  InputDecoration _inputDecoration() {
    return InputDecoration(
      // 未获得焦点下划线设为灰色
      enabledBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: AppColor.MAIN_COLOR_BLUE),
      ),
      //获得焦点下划线设为蓝色
      focusedBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: AppColor.MAIN_COLOR_BLUE),
      ),
    );
  }

  // 注册按钮
  Widget _registerButton() {
    Widget _streamRegisterButton = StreamBuilder<bool>(
      stream: _disableShowStream.stream,
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot){
        return RaisedButton(
          color: AppColor.MAIN_COLOR_CYAN,
          disabledColor: AppColor.MAIN_COLOR_CYAN_DISABLE,
          onPressed: null,
          child: LanguageText.registerText,
          textColor: AppColor.MAIN_COLOR_BLUE,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(SFunCommon.width(20))),
        );
      },
    );

    Widget _button = Container(
      margin: EdgeInsets.only(
        top: SFunCommon.height(100),
      ),
      width: SFunCommon.width(569),
      height: SFunCommon.height(75),
      child: _streamRegisterButton,
    );

    return Container(
      margin: EdgeInsets.only(
        right: SFunCommon.width(30),
        bottom: SFunCommon.height(80),
      ),
      alignment: Alignment.center,
      child: _button,
    );
  }
}
